package com.bobo.medicinechest.dialog;

import android.content.Context;
import android.os.CountDownTimer;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bobo.medicinechest.R;
import com.bobo.medicinechest.adapter.ShopCarAdapter;
import com.bobo.medicinechest.bean.GoodsBean;
import com.bobo.medicinechest.bean.GoodsTypeBean;
import com.bobo.medicinechest.databinding.DialogShopCarBinding;
import com.bobo.medicinechest.manager.CartManager;
import com.bobo.medicinechest.util.PriceFormatUtil;
import com.lxj.xpopup.core.CenterPopupView;
import com.lxj.xpopup.util.XPopupUtils;
import com.xuexiang.xui.widget.divider.CustomColorItemDecoration;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 购物车Dialog
 * liumeng
 */
public class ShopCarDialog extends CenterPopupView {

    private Context mContext;
    private List<GoodsBean> mGoodsList;
    private DialogShopCarBinding binding;
    private CountDownTimer countDownTimer;
    private List<GoodsBean> goodsListBeanList = new ArrayList<>();

    public ShopCarDialog(@NonNull Context context, List<GoodsBean> list) {
        super(context);
        this.mContext = context;
        this.mGoodsList = list;
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_shop_car;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        binding = DialogShopCarBinding.bind(getPopupImplView());
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        if (binding.recyclerView.getItemDecorationCount() == 0) {
            binding.recyclerView.addItemDecoration(new CustomColorItemDecoration(mContext, LinearLayoutManager.VERTICAL));
        }
        //初始化倒计时
        initCountDownTimer();
        binding.tvBack.setOnClickListener(v -> {
            countDownTimer.cancel();
            dismiss();
        });
        binding.tvPay.setOnClickListener(v -> {
            List<GoodsBean> cartList = CartManager.getInstance().getCartList();
            for (GoodsBean goodsBean:cartList ) {
                LogUtils.e(goodsBean.getName() + " Number="+ goodsBean.getNumber());
            }
            ToastUtils.showShort(CartManager.getInstance().getTotalCount() + " price="+CartManager.getInstance().getTotalPrice());
        });

        ShopCarAdapter mAdapter = new ShopCarAdapter(mGoodsList);
        binding.recyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            GoodsBean goodsBean = mAdapter.getData().get(position);
            switch (view.getId()) {
                case R.id.iv:
//                    View itemView = adapter.getViewByPosition(binding.recyclerView, position, R.id.space);
//                    String content = "最大功率"+ ((GoodsListBean.GoodsBean) adapter.getData().get(position)).getMaxPower();
//                    new XPopup.Builder(getContext())
//                            .isTouchThrough(true)
//                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//                            .atView(itemView)
//                            .asCustom(new ChargeDevicePopup(mContext, content))
//                            .show();
                    break;
                case R.id.ivMinus:
                    for (int i = 0; i < mGoodsList.size(); i++) {
                        GoodsBean goods = mGoodsList.get(i);
                        if (goods.getId().equals(goodsBean.getId())) {
                            int currentNumber = goods.getNumber();
                            if (currentNumber > 1) {
                                // 数量大于1，减少1
                                goods.setNumber(currentNumber - 1);
                            } else {
                                // 数量为1，移除商品
                                ToastUtils.showLong("购买数量不能少于1哟~");
                            }
                            break;
                        }
                    }
                    mAdapter.notifyItemChanged(position);

                    CartManager.getInstance().minusGoodsNumber(goodsBean.getId());
                    binding.tvTotalNum.setText("共"+ CartManager.getInstance().getTotalCount()+ "件 合计");
                    binding.tvTotalPrice.setText(PriceFormatUtil.formatPrice(CartManager.getInstance().getTotalPrice(), 17, 25, 19));
                    break;
                case R.id.ivAdd:
//                    for (int i = 0; i < mGoodsList.size(); i++) {
//                        GoodsBean goods = mGoodsList.get(i);
//                        if (goods.getId().equals(goodsBean.getId())) {
//                            if (goods.getNumber() == goods.getBuyNumber()) {
//                                ToastUtils.showLong("购买数量不能超过库存哟~");
//                                return;
//                            }
//                            // 商品已存在，数量+1
//                            goods.setBuyNumber(goods.getBuyNumber() + 1);
//                            break;
//                        }
//                    }
//                    mAdapter.notifyItemChanged(position);
//
//                    CartManager.getInstance().addGoodsToCart(goodsBean);
//                    binding.tvTotalNum.setText("共"+ CartManager.getInstance().getTotalCount()+ "件 合计");
//                    binding.tvTotalPrice.setText(PriceFormatUtil.formatPrice(CartManager.getInstance().getTotalPrice(), 17, 25, 19));
                    break;
                case R.id.ivDelete:
//                    for (int i = 0; i < mGoodsList.size(); i++) {
//                        if (mGoodsList.get(i).getId().equals(goodsBean.getId())) {
//                            mGoodsList.remove(i);
//                            mAdapter.notifyDataSetChanged();
//                            break;
//                        }
//                    }
                    mGoodsList.remove(position);
                    mAdapter.notifyDataSetChanged();

                    CartManager.getInstance().removeGoodsFromCart(goodsBean.getId());
                    binding.tvTotalNum.setText("共"+ CartManager.getInstance().getTotalCount()+ "件 合计");
                    binding.tvTotalPrice.setText(PriceFormatUtil.formatPrice(CartManager.getInstance().getTotalPrice(), 17, 25, 19));
                    break;
            }
        });

        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            GoodsBean goodsListBean = mAdapter.getData().get(position);
        });

    }

    private void initCountDownTimer() {
        // 创建倒计时器
        countDownTimer = new CountDownTimer(300000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // 每秒更新一次文本
                int seconds = (int) (millisUntilFinished / 1000);
                binding.tvBack.setText(String.format(Locale.getDefault(), "返回(%ds)", seconds));
            }

            @Override
            public void onFinish() {
                binding.tvBack.setText("返回(0s)");
                dismiss();
            }
        };
        countDownTimer.start();
    }


    @Override
    protected int getMaxHeight() {
        return (int) Math.round(XPopupUtils.getScreenHeight(mContext) * 0.7);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }
}
